package org.infinitest.intellij.idea.language;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.psi.PsiElement;
import org.infinitest.TestEvent;
import org.infinitest.intellij.InfinitestAnnotator;
import static org.infinitest.intellij.idea.language.IdeaElement.element;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class IdeaInfinitestAnnotator implements InfinitestAnnotator {
  private Set<TestEvent> testEvents = new HashSet<TestEvent>();

  public void annotate(PsiElement psiElement, AnnotationHolder holder) {
    for (TestEvent event : testEvents)
    {
      if (element(psiElement).matches(event))
      {
        holder.createErrorAnnotation(psiElement, event.getMessage());
      }
    }
  }

  public void annotate(TestEvent event) {
    testEvents.add(event);
    forceAnnotation();
  }

  public void clearAnnotation(TestEvent event) {
    testEvents.remove(event);
    forceAnnotation();
  }

  protected void forceAnnotation() {
    Project project = ProjectManager.getInstance().getOpenProjects()[0];
    DaemonCodeAnalyzer.getInstance(project).restart();
  }

  public Collection<TestEvent> listStoredEvents() {
    return testEvents;
  }
}
